package com.stylefeng.guns.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * respone返回信息工具类
 */
@Slf4j
public class ResponeContentUtils {

    private static final String DEFAULT_ENCODING = "UTF-8";

    public static void renderApplicationXml(HttpServletResponse response, String info) {
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType("text/xml;charset=utf-8");
        response.setHeader("content-type", "text/xml;charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.println(info);
            out.flush();
        } catch (Exception e) {
            log.error("renderApplicationXml", e);
        }
    }

    /**
     * 自定义输出ontent-type
     *
     * @param response
     * @param info
     * @param contentType
     */
    public static void render(HttpServletResponse response, String info, String contentType) {
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType(contentType);
        response.setHeader("content-type", contentType);
        try (PrintWriter out = response.getWriter()) {
            out.println(info);
            out.flush();
        } catch (Exception e) {
            log.error("render", e);
        }
    }

    public static void renderApplicationJson(HttpServletResponse response, String info) {
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("content-type", "application/json;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println(info);
            out.flush();
        } catch (Exception e) {
            log.error("renderApplicationJson", e);
        }
    }


    public static void renderNoHeader(HttpServletResponse response, String info) {
        try (PrintWriter out = response.getWriter()) {
            out.println(info);
            out.flush();
        } catch (Exception e) {
            log.error("renderNoHeader", e);
        }
    }

    public static void renderApplicationHtml(HttpServletResponse response, String info) {
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("content-type", "text/html;charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.println(info);
            out.flush();
        } catch (Exception e) {
            log.error("renderApplicationHtml", e);
        }
    }
}
